package com.yufubao.service.service.applet.product.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yufubao.framework.builder.es.RequestOptionsBuilder;
import com.yufubao.framework.constant.EsConstant;
import com.yufubao.framework.enums.CommonExceptionEnum;
import com.yufubao.framework.enums.SpuInfoPublishStatusEnum;
import com.yufubao.framework.exception.BaseException;
import com.yufubao.framework.interceptor.AppletInterceptor;
import com.yufubao.framework.interceptor.local.LoginUserLoc;
import com.yufubao.framework.result.PageUtils;
import com.yufubao.framework.util.CopyBean;
import com.yufubao.framework.util.MyCollUtil;
import com.yufubao.framework.util.page.Query;
import com.yufubao.model.dto.applet.discounts.SkuDiscountsEtcDto;
import com.yufubao.model.dto.applet.product.SpuQueryPageDetailDto;
import com.yufubao.model.dto.applet.product.spu.*;
import com.yufubao.model.pojo.applet.elasticsearch.SupplierEsModel;
import com.yufubao.model.pojo.applet.product.*;
import com.yufubao.service.mapper.applet.product.SpuInfoDao;
import com.yufubao.service.service.applet.discounts.SkuFullReductionService;
import com.yufubao.service.service.applet.product.*;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.support.WriteRequest;
import org.elasticsearch.action.support.replication.ReplicationResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.core.TimeValue;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import static com.yufubao.framework.enums.CommonExceptionEnum.ES_ERROR;
import static com.yufubao.framework.util.SecurityUtils.checkUserLoc;


@Service("spuInfoService")
@Slf4j
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    private SpuInfoDescService spuInfoDescService;

    @Autowired
    private SpuImagesService spuImagesService;

    @Autowired
    private AttrService attrService;

    @Autowired
    private ProductAttrValueService productAttrValueService;

    @Autowired
    private SkuFullReductionService skuFullReductionService;

    @Autowired
    private SkuInfoService skuInfoService;

    @Autowired
    private SkuImagesService skuImagesService;

    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;


    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Autowired
    private SupplierInfoService supplierInfoService;

    @Autowired
    private SupplierProductCategoryService supplierProductCategoryService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * @param dto
     * @return void
     * @description 商家发布商品
     * @author zhangyiheng
     * @date 2024/8/29 16:18
     */
    @Override
    @Transactional
    public void saveDetail(SpuSaveDto dto) {
        LoginUserLoc loginUserLoc = checkUserLoc(AppletInterceptor.APPLETTHREADLOCAL);

        if (Objects.isNull(loginUserLoc.getUserId())) {
            throw new BaseException(CommonExceptionEnum.NOAUTH);
        }

        if (Objects.isNull(loginUserLoc.getSupplierInfoIds())) {
            throw new BaseException(CommonExceptionEnum.NOT_PERMISSION);
        }

        //判断用户是否是此商店注册人
        boolean res = false;
        res = loginUserLoc.getSupplierInfoIds().stream().anyMatch(id -> id.equals(dto.getSupplierInfoId()));
        if (!res) {
            throw new BaseException(CommonExceptionEnum.NOT_PERMISSION);
        }


        //region 1、保存spu基本信息、pms_spu_info
        SpuInfoEntity spuInfoEntity = saveSpuInfoEntity(dto);
        //endregion

        Long spuId = spuInfoEntity.getId();


        //region 2、保存Spu的描述图片pms_spu_info_desc
        saveSpuInfoDescEntity(dto, spuId);
        //endregion


        //region 3、保存spu的图片集 pms_spu_images
        saveSpuImagesEntity(dto, spuId);
        //endregion


        //region 4、保存spu的规格参数;pms_product_attr_value
        saveProductAttrValueEntity(dto, spuId);
        //endregion


        //region 5、保存spu的积分信息；gulimall_sms-> sms_spu_bounds
        //TODO 用户积分系统
        // saveSpuBounds(dto, spuId);
        //endregion


        //region 6、保存当前spu对应的所有sku信息；
        List<Skus> skus = dto.getSkus();
        if (CollUtil.isNotEmpty(skus)) {
            List<SkuDiscountsEtcDto> skuDiscountsEts = new ArrayList<>();
            for (Skus sku : skus) {

                //region 6.1）、sku的基本信息；pms_sku_info
                SkuInfoEntity skuInfoEntity = CopyBean.copyBean(sku, SkuInfoEntity.class);
                skuInfoEntity.setSpuId(spuId);
                skuInfoEntity.setSupplierInfoId(dto.getSupplierInfoId());
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                if (CollUtil.isNotEmpty(sku.getImages())) {
                    sku.getImages().forEach(po -> {
                        if (po.getDefaultImg() == 1) {
                            skuInfoEntity.setSkuDefaultImg(po.getImgUrl());
                        }
                    });
                }
                skuInfoEntity.setSaleCount(0L);
                skuInfoService.save(skuInfoEntity);
                //endregion

                Long skuId = skuInfoEntity.getSkuId();

                //region 6.2）、sku的图片信息；pms_sku_images
                saveSkuImagesEntity(sku, skuId);
                //endregion


                //region  6.3）、sku的销售属性信息：pms_sku_saLe_attr_vaLue
                saveSkuSaleAttrValueEntity(sku, skuId);
                //endregion

                // 6.4）、sku的优惠、满减等信息；guLimaLL_sms->sms_sku_Ladder\sms_sku_fuLL_reduction\sms_member_price
                if (sku.getFullCount() > 0 || sku.getFullPrice().compareTo(new BigDecimal(0)) > 0) {
                    SkuDiscountsEtcDto skuDiscountsEtc = CopyBean.copyBean(sku, SkuDiscountsEtcDto.class);
                    skuDiscountsEtc.setSkuId(skuId);
                    skuDiscountsEts.add(skuDiscountsEtc);
                }
            }

            if (CollUtil.isNotEmpty(skuDiscountsEts)) {
                res = skuFullReductionService.saveSkuDiscountsEtc(skuDiscountsEts);
                if (!res) {
                    throw new BaseException("保存sku的优惠、满减等信息失败");
                }
            }
        }
        log.info("商品信息保存完成，商店用户id：{}，商店id：{}", loginUserLoc.getUserId(), dto.getSupplierInfoId());
        //endregion
    }

    /**
     * @param dto
     * @return com.zhangzhan.gulimallproduct.entity.SpuInfoEntity
     * @description 保存spu基本信息、pms_spu_info
     * @author zhangyiheng
     * @date 2024/6/18 3:15
     */
    private SpuInfoEntity saveSpuInfoEntity(SpuSaveDto dto) {
        SpuInfoEntity spuInfoEntity = CopyBean.copyBean(dto, SpuInfoEntity.class);
        this.save(spuInfoEntity);
        return spuInfoEntity;
    }

    /**
     * @param dto
     * @param spuId
     * @return void
     * @description 2、保存Spu的描述图片pms_spu_info_desc
     * @author zhangyiheng
     * @date 2024/6/18 3:16
     */
    private void saveSpuInfoDescEntity(SpuSaveDto dto, Long spuId) {
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(spuId);
        if (CollUtil.isNotEmpty(dto.getDecript())) {
            spuInfoDescEntity.setDecript(String.join(",", dto.getDecript()));
        }
        spuInfoDescService.save(spuInfoDescEntity);
    }


    /**
     * @param dto
     * @param spuId
     * @return void
     * @description 3、保存spu的图片集 pms_spu_images
     * @author zhangyiheng
     * @date 2024/6/18 3:16
     */
    private void saveSpuImagesEntity(SpuSaveDto dto, Long spuId) {
        List<SpuImagesEntity> spuImagesEntities = new ArrayList<>();
        List<String> images = dto.getImages();
        if (CollUtil.isNotEmpty(images)) {
            images.forEach(po -> {
                SpuImagesEntity spuImagesEntity = new SpuImagesEntity();
                spuImagesEntity.setSpuId(spuId);
                spuImagesEntity.setImgUrl(po);
                spuImagesEntities.add(spuImagesEntity);
            });
            spuImagesService.saveBatch(spuImagesEntities);
        }
    }


    /**
     * @param dto
     * @param spuId
     * @return void
     * @description 4、保存spu的规格参数;pms_product_attr_value
     * @author zhangyiheng
     * @date 2024/8/29 16:22
     */
    private void saveProductAttrValueEntity(SpuSaveDto dto, Long spuId) {
        List<BaseAttrs> baseAttrs = dto.getBaseAttrs();
        if (CollUtil.isNotEmpty(baseAttrs)) {
            List<ProductAttrValueEntity> productAttrValueEntities = baseAttrs.stream().map(po -> {
                ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
                productAttrValueEntity.setSpuId(spuId);
                productAttrValueEntity.setAttrId(po.getAttrId());
                productAttrValueEntity.setAttrValue(po.getAttrValues());
                productAttrValueEntity.setQuickShow(po.getShowDesc());
                AttrEntity attr = attrService.getById(po.getAttrId());
                if (!Objects.isNull(attr)) {
                    productAttrValueEntity.setAttrName(attr.getAttrName());
                }
                return productAttrValueEntity;
            }).collect(Collectors.toList());
            productAttrValueService.saveBatch(productAttrValueEntities);
        }
    }

    /**
     * @param sku
     * @param skuId
     * @return void
     * @description 6.2）、sku的图片信息；pms_sku_images
     * @author zhangyiheng
     * @date 2024/6/18 3:17
     */
    private void saveSkuImagesEntity(Skus sku, Long skuId) {
        List<Images> skuImages = sku.getImages();
        if (CollUtil.isNotEmpty(skuImages)) {
            List<SkuImagesEntity> skuImagesEntities = new ArrayList<>(skuImages.stream().map(po -> {
                if (StrUtil.isNotBlank(po.getImgUrl())) {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuId);
                    skuImagesEntity.setImgUrl(po.getImgUrl());
                    skuImagesEntity.setDefaultImg(po.getDefaultImg());
                    return skuImagesEntity;
                }
                return null;
            }).collect(Collectors.toList()));
            skuImagesEntities.removeAll(Collections.singleton(null));
            skuImagesService.saveBatch(skuImagesEntities);
        }
    }


    /**
     * @param sku
     * @param skuId
     * @return void
     * @description 6.3）、sku的销售属性信息：pms_sku_saLe_attr_vaLue
     * @author zhangyiheng
     * @date 2024/6/18 3:17
     */
    private void saveSkuSaleAttrValueEntity(Skus sku, Long skuId) {
        List<Attr> attr = sku.getAttr();
        if (CollUtil.isNotEmpty(attr)) {
            List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = attr.stream().map(po -> {
                SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                skuSaleAttrValueEntity.setSkuId(skuId);
                skuSaleAttrValueEntity.setAttrId(po.getAttrId());
                skuSaleAttrValueEntity.setAttrName(po.getAttrName());
                skuSaleAttrValueEntity.setAttrValue(po.getAttrValue());

                return skuSaleAttrValueEntity;
            }).collect(Collectors.toList());

            skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);
        }
    }

    /**
     * @param dto
     * @return com.yufubao.framework.result.PageUtils
     * @description 查询当前商店的spu信息
     * @author zhangyiheng
     * @date 2024/8/30 10:07
     */
    @Override
    public PageUtils queryPageDetail(SpuQueryPageDetailDto dto) {
        //模糊检索条件
        String key = dto.getKey();
        //上下架状态
        Integer status = dto.getStatus();
        //品牌id
//        Object brandId = params.get("brandId");
        //分类id
        Long catelogId = dto.getCatelogId();
        Long supplierInfoId = dto.getSupplierInfoId();

        LambdaQueryWrapper<SpuInfoEntity> wrapper = new LambdaQueryWrapper<>();
        if (StrUtil.isNotBlank(key)) {
            wrapper.and(po -> {
                po.eq(SpuInfoEntity::getId, key).or().like(SpuInfoEntity::getSpuName, key);
            });
        }

        wrapper.eq(SpuInfoEntity::getSupplierInfoId, supplierInfoId);
        wrapper.eq(!Objects.isNull(status), SpuInfoEntity::getPublishStatus, status);
//        wrapper.eq(!Objects.isNull(brandId) && !Objects.equals(brandId, "0"), SpuInfoEntity::getBrandId, brandId);
        wrapper.eq(!Objects.isNull(catelogId) && !Objects.equals(catelogId, 0L), SpuInfoEntity::getCatalogId, catelogId);

        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(JSON.parseObject(JSON.toJSONString(dto), Map.class)),
                wrapper
        );

        return new PageUtils(page);
    }


    /**
     * @param spuId
     * @return void
     * @description 商品上架 保存检索信息到es并更新相关状态
     * @author zhangyiheng
     * @date 2024/9/1 15:40
     */
    @Override
    @Transactional
    public void up(Long spuId) {

        LoginUserLoc loginUserLoc = checkUserLoc(AppletInterceptor.APPLETTHREADLOCAL);

        //校验商户
        SupplierInfoEntity supplierInfo = supplierInfoService.getById(spuId);
        Long supplierInfoId = supplierInfo.getSupplierInfoId();
        List<Long> supplierInfoIds = loginUserLoc.getSupplierInfoIds();
        //查询在es中是否存在当前商店，如果存在判断spu属性，如果相同不做操作，如果不同追加替换，如果不存在商店构建数据直接保存es
        List<SupplierEsModel.Attrs> attrs = null;
        if (supplierInfoIds.contains(supplierInfoId)) {
            //查询es
            SearchRequest searchRequest = new SearchRequest(EsConstant.SUPPLIER_INDEX);
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
            BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();

            //查询当前spu商品属性信息  过滤不需要检索的商品属性
            attrs = getAttrs(spuId);

            //查询当前商户是否存在es
            SearchHits hits = getSearchHits(boolQueryBuilder, supplierInfoId, searchSourceBuilder, searchRequest);

            SupplierEsModel supplierEsModel = null;
            if (hits.getHits() == null || hits.getHits().length == 0) {
                //不存在直接构建数据存入es
                supplierEsModel = firstEs(supplierInfoId, supplierInfo, attrs);

            } else {
                //存在校验属性是否重复，没有重复追加，重复不做操作
                SearchHit[] data = hits.getHits();
                for (SearchHit hit : data) {
                    String dataJson = hit.getSourceAsString();
                    supplierEsModel = JSON.parseObject(dataJson, SupplierEsModel.class);
                    //当前spu对应的属性值
                    attrs = getAttrs(spuId);
                    //旧spu属性值
                    List<SupplierEsModel.Attrs> spuAttrs = supplierEsModel.getSpuAttrs();

                    if (MyCollUtil.isNotEmpty(attrs)) {
                        if (MyCollUtil.isNotEmpty(spuAttrs)) {
                            //如果都不为空处理重复元素
                            List<Integer> index = new ArrayList<>();
                            for (int i = 0; i < attrs.size(); i++) {
                                for (SupplierEsModel.Attrs spuAttr : spuAttrs) {
                                    List<String> list = new ArrayList<>();
                                    if (attrs.get(i).getAttrId().equals(spuAttr.getAttrId())) {
                                        list.addAll(spuAttr.getAttrValue());
                                        list.addAll(attrs.get(i).getAttrValue());
                                        spuAttr.setAttrValue(list);
                                        index.add(i);
                                    }
                                }
                            }

                            //删除重复元素
                            if (MyCollUtil.isNotEmpty(index)) {
                                for (Integer i : index) {
                                    attrs.remove(i.intValue());
                                }
                            }

                            if (MyCollUtil.isNotEmpty(attrs)) {
                                spuAttrs.addAll(attrs);
                            }

                            //去重
                            for (SupplierEsModel.Attrs spuAttr : spuAttrs) {
                                spuAttr.setAttrValue(spuAttr.getAttrValue().stream().distinct().collect(Collectors.toList()));
                            }

                            supplierEsModel.setSpuAttrs(spuAttrs);
                        } else {
                            //旧集合为空追加
                            spuAttrs.addAll(attrs);
                            supplierEsModel.setSpuAttrs(spuAttrs);
                        }
                    }
                }
            }
            //存入es
            saveSupplierToSearch(supplierEsModel);
            log.info("商品上架es保存商户信息成功，supplierInfoId：{}", supplierInfoId);

            //修改上架状态
            this.update(Wrappers.<SpuInfoEntity>lambdaUpdate()
                    .set(SpuInfoEntity::getPublishStatus, SpuInfoPublishStatusEnum.SJ_TYPE.getCode())
                    .eq(SpuInfoEntity::getId, spuId));

            log.info("商品上架成功，supplierInfoId：{}，spuId：{}", supplierInfoId, spuId);
        } else {
            throw new BaseException(CommonExceptionEnum.NOT_PERMISSION);
        }
    }

    /**
     * @param supplierEsModel
     * @return void
     * @description 保存es商户信息
     * @author zhangyiheng
     * @date 2024/9/1 22:02
     */
    @Override
    public void saveSupplierToSearch(SupplierEsModel supplierEsModel) {
        IndexRequest indexRequest = new IndexRequest(EsConstant.SUPPLIER_INDEX);
        //id设为商户id
        indexRequest.id(supplierEsModel.getSupplierInfoId().toString());

        String modelJson = JSON.toJSONString(supplierEsModel);
        indexRequest.source(modelJson, XContentType.JSON);

        //数据覆盖
        indexRequest.create(false);
        indexRequest.timeout(TimeValue.timeValueSeconds(5));
        indexRequest.setRefreshPolicy(WriteRequest.RefreshPolicy.WAIT_UNTIL);

        //单个实例异步存储
        restHighLevelClient.indexAsync(indexRequest, RequestOptionsBuilder.COMMON_OPTIONS, new ActionListener<IndexResponse>() {
            @Override
            public void onResponse(IndexResponse indexResponse) {
                ReplicationResponse.ShardInfo shardInfo = indexResponse.getShardInfo();
                if (shardInfo.getFailed() > 0) {
                    for (ReplicationResponse.ShardInfo.Failure failure : shardInfo.getFailures()) {
                        log.error("将supplierInfoId为：{}的数据存入ES时存在失败的分片，原因为：{}", indexRequest.id(), failure.getCause());
                        throw new BaseException(ES_ERROR);
                    }
                }
            }

            /**
             * A failure caused by an exception at some phase of the task.
             *
             * @param e
             */
            @Override
            public void onFailure(Exception e) {
                log.error("supplierInfoId:{}:存储es时异常，数据信息为:{}", indexRequest.id(), e);
                throw new BaseException(ES_ERROR);
            }
        });
    }

    /**
     * 构建商户es元素
     *
     * @param supplierInfoId
     * @param supplierInfo
     * @param attrs
     * @return
     */
    @Override
    public SupplierEsModel firstEs(Long supplierInfoId, SupplierInfoEntity supplierInfo, List<SupplierEsModel.Attrs> attrs) {
        SupplierEsModel supplierEsModel = new SupplierEsModel();
        supplierEsModel.setSupplierInfoId(supplierInfoId);
        supplierEsModel.setStoreName(supplierInfo.getStoreName());
        supplierEsModel.setAddress(supplierInfo.getArea() + supplierEsModel.getAddress());
        supplierEsModel.setSupplierSubtitle(supplierEsModel.getSupplierSubtitle());
        supplierEsModel.setHotScore(supplierInfo.getHotScore());
        supplierEsModel.setShopFrontUrl(supplierInfo.getShopFrontUrl());
        if (!Objects.isNull(supplierInfo.getDayOfWeek())){
            supplierEsModel.setDayOfWeek(supplierInfo.getDayOfWeek());
        }
        if (!Objects.isNull(supplierInfo.getOpenTime())){
            supplierEsModel.setOpenTime(supplierInfo.getOpenTime().toString());
        }
        if (!Objects.isNull(supplierInfo.getEndTime())){
            supplierEsModel.setEndTime(supplierInfo.getEndTime().toString());
        }
        if (!Objects.isNull(supplierInfo.getIsHoliday())){
            supplierEsModel.setIsHoliday(supplierInfo.getIsHoliday());
        }
        //查询分类信息
        supplierEsModel.setCategoryId(supplierInfo.getCategoryId());
        SupplierProductCategoryEntity category = supplierProductCategoryService.getById(supplierInfo.getCategoryId());
        supplierEsModel.setCategoryName(category.getName());
        supplierEsModel.setSpuAttrs(attrs);
        return supplierEsModel;
    }


    /**
     * 查询es商户是否存在
     *
     * @param boolQueryBuilder
     * @param supplierInfoId
     * @param searchSourceBuilder
     * @param searchRequest
     * @return
     */
    private SearchHits getSearchHits(BoolQueryBuilder boolQueryBuilder, Long supplierInfoId, SearchSourceBuilder searchSourceBuilder, SearchRequest searchRequest) {
        SearchResponse search = null;
        try {
            boolQueryBuilder.should(QueryBuilders.termQuery("supplierInfoId", supplierInfoId));
            searchSourceBuilder.query(boolQueryBuilder);
            searchRequest.source(searchSourceBuilder);

            search = restHighLevelClient.search(searchRequest, RequestOptionsBuilder.COMMON_OPTIONS);
        } catch (IOException e) {
            log.error(ES_ERROR.getMsg(), e.getMessage());
            throw new BaseException(ES_ERROR);
        }
        return search.getHits();
    }


    /**
     * 查询商品属性信息  过滤不需要检索的商品属性
     *
     * @param spuId
     * @return
     */
    private List<SupplierEsModel.Attrs> getAttrs(Long spuId) {
        List<ProductAttrValueEntity> productAttrValueEntities = productAttrValueService.list(Wrappers.<ProductAttrValueEntity>lambdaQuery()
                .eq(ProductAttrValueEntity::getSpuId, spuId));

        List<Long> attrIds = productAttrValueEntities.stream().map(ProductAttrValueEntity::getAttrId).collect(Collectors.toList());

        List<AttrEntity> attrEntityList = attrService.list(Wrappers.<AttrEntity>lambdaQuery()
                .in(AttrEntity::getAttrId, attrIds));

        List<Long> attrIds2 = attrEntityList.stream().filter(po -> Objects.equals(po.getSearchType(), 1)).map(AttrEntity::getAttrId).collect(Collectors.toList());

        List<SupplierEsModel.Attrs> attrs = new ArrayList<>();

        if (CollUtil.isNotEmpty(attrIds2)) {
            List<ProductAttrValueEntity> productAttrValueEntities2 = productAttrValueEntities.stream().filter(po -> attrIds2.contains(po.getAttrId())).collect(Collectors.toList());


            if (CollUtil.isNotEmpty(productAttrValueEntities2)) {
                Map<Long, List<ProductAttrValueEntity>> map = productAttrValueEntities2.stream().collect(Collectors.groupingBy(ProductAttrValueEntity::getAttrId));

                for (Map.Entry<Long, List<ProductAttrValueEntity>> entry : map.entrySet()) {
                    SupplierEsModel.Attrs attr = new SupplierEsModel.Attrs();
                    attr.setAttrId(entry.getKey());
                    attr.setAttrName(entry.getValue().get(0).getAttrName());
                    List<String> list = new ArrayList<>();
                    for (ProductAttrValueEntity productAttrValueEntity : entry.getValue()) {
                        list.add(productAttrValueEntity.getAttrValue());
                    }
                    attr.setAttrValue(list);
                    attrs.add(attr);
                }

                return attrs;
            }
        }
        return null;
    }

}